<template>
  <div class="main">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>成员管理</span>
        <el-button
        style="float: right;"
          @click="openAddMemberdialogVisible()"
          type="primary"
          icon="el-icon-user"
          >邀请成员</el-button
        >
      </div>
      <div style="background-color: white">
        <el-input
          prefix-icon="el-icon-search"
          v-model="user.userName"
          placeholder="搜索成员名"
        ></el-input>
        <el-button
          icon="el-icon-search"
          type="primary"
          circle
          @click="getDate()"
        ></el-button>
        <el-button
          icon="el-icon-refresh-left"
          @click="reset()"
          type="info"
          circle
        ></el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column v-if="false" prop="id" label="id"> </el-table-column>
        <el-table-column
          prop="userName"
          label="用户名"
          width="130"
        ></el-table-column>
        <el-table-column
          prop="telephone"
          label="手机号"
          width="130"
        ></el-table-column>
        <el-table-column prop="sex" label="性别" width="100"> </el-table-column>
        <el-table-column prop="teamName" label="所属团队"> </el-table-column>
        <el-table-column prop="birthday" label="生日"> </el-table-column>
        <el-table-column property="relationshipType" label="角色">
          <template slot-scope="scope">
            <span v-if="scope.row.relationshipType == 1">队长</span>
            <span v-if="scope.row.relationshipType == 2">成员</span>
            <span v-if="scope.row.relationshipType == 3">管理员</span>
          </template>
        </el-table-column>
        <el-table-column prop="perSignature" label="个性签名">
        </el-table-column>
        <el-table-column prop="createTime" label="加入时间"> </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-popconfirm
              title="您确定删除这个成员么？"
              cancel-button-text="算了算了"
              @confirm="handleDel(scope.row.id, scope.row.teamId)"
            >
              <el-button
                slot="reference"
                type="danger"
                icon="el-icon-delete"
                circle
              ></el-button>
            </el-popconfirm>
            <el-tooltip
              class="item"
              effect="dark"
              content="设为管理员"
              placement="top-end"
            >
              <el-button
                v-if="scope.row.relationshipType == 2"
                type="warning"
                icon="el-icon-edit"
                @click="changeToMange(scope.row, 3, 5, '管理员')"
                circle
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="设为成员"
              placement="top-end"
            >
              <el-button
                v-if="scope.row.relationshipType == 3"
                type="warning"
                icon="el-icon-edit"
                @click="changeToMange(scope.row, 2, 4, '成员')"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination
          :total="total"
          :pageNum="pageNum"
          :pageSize="pageSize"
          @changePageSize="changePageSize"
          @changePageNum="changePageNum"
        ></pagination>
      </div>
    </el-card>
    <el-drawer
      :title="formTitle"
      size="35%"
      :visible.sync="drawerDialog"
      :direction="direction"
      :before-close="handleClose"
    >
      <div class="drawerForm">
        <el-form
          :model="addUserForm"
          ref="addUserForm"
          label-width="180px"
          :rules="rules"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="addUserForm.userName"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              :show-password="true"
              v-model="addUserForm.password"
              type="password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="addUserForm.sex" placeholder="请选择">
              <el-option
                v-for="item in sexOptions"
                :key="item.value"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="telephone">
            <el-input
              v-model="addUserForm.telephone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="团队名称" prop="teamName">
            <el-select v-model="addUserForm.teamName" placeholder="请选择">
              <el-option
                v-for="item in teamList[0]"
                :key="item.teamName"
                :value="item.teamName"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="addUserForm.birthday"
              type="date"
              placeholder="选择日期"
              style="width: 200px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="个性签名" prop="perSignature">
            <el-input
              v-model="addUserForm.perSignature"
              type="textarea"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <el-dialog
      title="邀请成员"
      :visible.sync="addMemberdialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <div>
        <el-form>
          <el-form-item label="用户名">
            <el-input
              v-model="newTeamMemberName"
              style="width: 90%"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addMemberdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="invateUser()">邀请加入</el-button>
      </span>
    </el-dialog>
    <dialogConfirm ref="dialogConfirm"></dialogConfirm>
  </div>
</template>
<script>
import { listPage, add, updateById, listUser } from "@/api/user";
import { LoDeletedUserAndTeamRea, updateTeamUser } from "@/api/teamUser";
import { updateUserRole } from "@/api/role";
import { list } from "@/api/team";
import Pagination from "@/components/Pagination/index";
import DialogConfirm from "@/components/DialogConfirm/index";
import { addUserRole } from "@/api/role";
import { addUserAndTeamRea } from "@/api/teamUser";
export default {
  components: {
    Pagination,
    DialogConfirm,
  },
  data() {
    return {
      addMemberdialogVisible: false,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 10,
      drawerDialog: false,
      direction: "rtl",
      formTitle: "",
      user: {
        userName: "",
        password: "",
        telephone: "",
        sex: "",
        birthday: "",
        teamName: "",
        perSignature: "",
      },
      addUserForm: {
        id: "",
        userName: "",
        password: "",
        telephone: "",
        sex: "",
        birthday: "",
        teamName: "",
        perSignature: "",
      },
      sexOptions: [
        {
          value: "男",
        },
        {
          value: "女",
        },
      ],
      teamList: [],
      teamNameList: [],
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入11位数手机号",
            trigger: "blur",
          },
        ],
        perSignature: [
          {
            min: 0,
            max: 20,
            message: "字数不能超过20个",
            trigger: "blur",
          },
        ],
      },
      newTeamMemberName: "",
    };
  },
  methods: {
    changePageSize(val) {
      this.pageSize = val;
      this.getDate();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.getDate();
    },
    getDate() {
      console.log(this.user.userName);
      this.user.teamName = this.$store.getters.teamName;
      const param = {
        page: this.pageNum,
        limit: this.pageSize,
        userName: this.user.userName,
        sex: this.user.sex,
        teamName: this.user.teamName,
      };
      listPage(param).then((res) => {
        // console.log(res.data);
        this.total = res.total;
        this.tableData = res.data;
      });
    },
    reset() {
      this.user.userName = "";
      this.user.sex = "";
      this.user.teamName = "";
      this.getDate();
    },
    delete() {},
    openDialog(name, data) {
      console.log(this.drawerDialog.title);
      this.drawerDialog = true;
      if (name == "add") {
        this.resetAddForm(), (this.formTitle = "添加");
      }
      if (name == "edit") {
        this.formTitle = "编辑";
        this.addUserForm = {
          id: data.id,
          userName: data.userName,
          password: data.password,
          telephone: data.telephone,
          sex: data.sex,
          birthday: data.birthday,
          teamName: data.teamName,
          perSignature: data.perSignature,
        };
      }
    },
    handleClose() {
      console.log("关闭123");
      this.drawerDialog = false;
      this.resetAddForm();
    },

    changeToMange(user, relationshipType, roleId, roleName) {
      this.$confirm("此操作将修改用户为团队" + roleName, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const param = {
            userId: user.id,
            teamId: user.teamId,
            roleId: roleId,
          };
          updateUserRole(param).then((res) => {
            if (res.code == 0) {
              const teamUserParam = {
                userId: user.id,
                teamId: user.teamId,
                relationshipType: relationshipType,
              };
              updateTeamUser(teamUserParam).then((res) => {
                if (res.code == 0) {
                  this.$message({
                    message: "修改成功",
                    type: "success",
                  });
                }
              });
            }
          });
          this.getDate();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      console.log(user);
    },
    getTeam() {
      list().then((res) => {
        console.log(res.data);
        this.teamList.push(res.data);
      });
    },
    resetAddForm() {
      console.log("重置");
      this.addUserForm = {
        id: "",
        userName: "",
        password: "",
        telephone: "",
        sex: "",
        birthday: "",
        teamName: "",
        perSignature: "",
      };
    },
    async submitAddForm(formName) {
      if (this.formTitle == "添加") {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            add(this.addUserForm).then((res) => {
              if (res.code == 0) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: "添加失败",
                  type: "error",
                });
              }
            });
            this.drawerDialog = false;
          } else {
            this.$message({
              message: "您输入的信息不符合规范",
              type: "warning",
            });
          }
          this.getDate();
        });
      } else if (this.formTitle == "编辑") {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm("此操作将修改此用户信息, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                updateById(this.addUserForm).then((res) => {
                  if (res.code == 0) {
                    this.$message({
                      message: "修改成功",
                      type: "success",
                    });
                  } else {
                    this.$message({
                      message: "修改失败",
                      type: "error",
                    });
                  }
                  this.getDate();
                  this.drawerDialog = false;
                  this.resetAddForm();
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除",
                });
              });
          } else {
            this.$message({
              message: "您输入的信息不符合规范",
              type: "warning",
            });
          }
        });
      }
    },

    handleDel(userId, teamId) {
      console.log(userId + "----" + teamId);
      const teamUser = {
        userId: userId,
        teamId: teamId,
      };
      LoDeletedUserAndTeamRea(teamUser).then((res) => {
        this.getDate();
        if (res.code == 0) {
          this.$message({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
        } else {
          this.$message({
            showClose: true,
            message: "删除失败",
            type: "erorr",
          });
        }
      });
    },
    handleEdit() {},
    openAddMemberdialogVisible() {
      this.addMemberdialogVisible = true;
    },
    async invateUser() {
      var userArr = [];
      //查询所有用户
      await listUser().then((res) => {
        if (res.code == 0) {
          res.data.forEach((user) => {
            userArr.push(user.userName);
          });
        }
      });
      console.log(userArr);
      console.log(userArr.indexOf(this.newTeamMemberName));
      if (userArr.indexOf(this.newTeamMemberName) <= -1) {
        this.$message({
          message: "系统中不存在此用户，请确认用户名是否正确",
          type: "warning",
        });
      } else {
        const roleParam = {
          userName: this.newTeamMemberName,
          teamName: this.$store.getters.teamName,
          roleName: "团队成员",
        };
        const teamParam = {
          userName: this.newTeamMemberName,
          teamName: this.$store.getters.teamName,
          relationshipType: 2,
        };
        addUserAndTeamRea(teamParam).then((res) => {
          if (res.code == 0) {
            console.log("邀请成功");
          }
        });
        addUserRole(roleParam).then((res) => {
          if (res.code == 0) {
            this.$message({
              message: "邀请成功",
              type: "success",
            });
            this.activeName = "first";
          }
        });
      }
    },
  },
  mounted() {
    this.getDate();
    this.getTeam();
  },
};
</script>
<style lang="scss" scoped>
.el-input {
  width: 150px;
  padding: 10px;
}
.el-select {
  width: 150px;
}
.el-table-column {
  text-align: center;
}
.main {
  margin-left: 10px;
  height: 100vh;
}
.pagination {
  margin-top: 30px;
  text-align: center;
}
.el-input {
  width: 200px;
}
.el-textarea {
  width: 200px;
}
.el-select {
  width: 200px;
}
.el-card {
  height: 98%;
  margin-right: 20px;

}
</style>
